// 插件引入
const gulp = require('gulp');
const browserify = require('browserify');
const vueify = require('vueify');
const babelify = require('babelify');
const babel = require('gulp-babel');
const less = require('gulp-less');
const includer = require('gulp-content-includer');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const concat = require('gulp-concat');
const glob = require('glob');
const util = require('gulp-util');

// 进行 资源 拷贝
gulp.task('assets', function() {
    gulp.src('resource/assets/**').pipe(gulp.dest('public/'));
});


// 进行 LESS 编译
gulp.task('style', function() {
    let steam = gulp.src('resource/less/*.less');
    steam = steam.pipe(less());
    steam = steam.pipe(rename({suffix:'.min',extname:".css"}));
    steam.pipe(gulp.dest('public/styles'));
});

// 进行 HTML 编译
gulp.task('html', function() {
    let steam = gulp.src('resource/boots/*.html');
    let config = {includerReg:/<!\-\-include\s+"([^"]+)"\-\->/g};
    steam = steam.pipe(includer(config));
    steam.pipe(gulp.dest('public'));
});

// 进行 Script 编译
gulp.task('script', function(){
    // 合并依赖库
    gulp.src([
        'node_modules/vue/dist/vue.js'
    ]).pipe(concat('library.min.js')).pipe(gulp.dest('public/scripts'));

    // 拷贝兼容库
    gulp.src([
        'node_modules/html5shiv/dist/html5shiv.min.js',
        'node_modules/respond.js/dest/respond.min.js'
    ]).pipe(gulp.dest('public/scripts'));

    // 编译应用脚本
    let javascriptBrowserify = function(src, file, dir){
        browserify(src)
            .transform(vueify)
            .transform("babelify", {presets: ["es2015"]})
            .bundle()
            .pipe(source(file))
            //.pipe(uglify())
            .pipe(rename({suffix:'.min'}))
            .pipe(gulp.dest(dir));
    };
    glob('resource/app/*.js', {}, function(err, files) {
        for(let i=0; i<files.length; i++){
            let re_name = files[i].split('/').pop();
            javascriptBrowserify(files[i],re_name,'public/scripts')
        }
    });

});

gulp.task('build',['assets','style','html','script'], function() {
    // 拷贝前端依赖组件
    let copyComponents = function(files, dest){
        gulp.src('node_modules/'+files).pipe(gulp.dest(dest));
    };
    // 需要拷贝的前端依赖
    //copyComponents('bootstrap/fonts/*', 'public/fonts/');
    //copyComponents('font-awesome/fonts/*', 'public/fonts/');
    copyComponents('element-ui/lib/theme-default/fonts/*', 'public/styles/fonts/');
});

gulp.task('watch', function() {
    gulp.watch('resource/**', ['build']);
});